<script setup>
import BaseInput from '@/components/base/BaseInput.vue'
import PhoneCodeInput from '@/components/auth/PhoneCodeInput.vue'
import { ref, watch } from 'vue'
import BaseButton from '@/components/base/BaseButton.vue'
import { updatePhone } from '@/api/user'
import { useStore } from 'vuex'
import useLocale from '@/composables/useLocale'

const store = useStore()
const { t, locale } = useLocale()

const formRef = ref(null)
const formData = ref({
    phone: '',
    code: '',
})

watch(
    locale,
    () => {
        uni.setNavigationBarTitle({
            title: t('changePhoneNumber'),
        })
    },
    { immediate: true },
)
const fields = {
    phone: {
        placeholder: t('pleaseEnterNewPhoneNumber'),
        type: 'tel',
        inputmode: 'tel',
        rules: [
            {
                required: true,
                errorMessage: t('pleaseEnterPhoneNumber'),
            },
            {
                pattern: /^1[3-9]\d{9}$/,
                errorMessage: t('pleaseEnterValidPhoneNumber'),
            },
        ],
    },
    code: {
        placeholder: t('pleaseEnterCode'),
        rules: [
            {
                required: true,
                errorMessage: t('pleaseEnterCode'),
            },
        ],
    },
}

async function handleSubmit() {
    try {
        const data = await formRef.value.validate()
        uni.showLoading()
        const resp = await updatePhone(data)
        uni.hideLoading()
        if (resp.status === 200) {
            store.dispatch('user/setUser')
            uni.showToast({
                title: t('changeSuccess'),
                icon: 'none',
                success() {
                    uni.navigateBack()
                },
            })
        }
    } catch (_) {
        /* empty */
    }
}
</script>

<template>
    <view class="flex justify-center px-8">
        <view class="flex w-full max-w-96 flex-col gap-3 pt-12">
            <uni-forms ref="formRef" :model-value="formData">
                <uni-forms-item
                    v-for="({ rules, ...attrs }, name) in fields"
                    :key="name"
                    :rules="rules"
                    :name="name"
                >
                    <!-- 小程序不支持 <component is="" /> 的写法-->
                    <BaseInput
                        v-if="name !== 'code'"
                        v-bind="attrs"
                        v-model="formData[name]"
                    />
                    <PhoneCodeInput
                        v-else
                        v-bind="attrs"
                        v-model="formData[name]"
                        :phone="formData.phone"
                    />
                </uni-forms-item>
            </uni-forms>
            <BaseButton @click="handleSubmit">
                {{ t('confirmChange') }}
            </BaseButton>
        </view>
    </view>
</template>
